//
//  DRBluetoothManager.m
//  DoctorRen
//
//  Created by Lemon on 2018/11/22.
//

#import "DRBluetoothManager.h"
#import "OSZDataTool.h"

@interface DRBluetoothManager()<CBCentralManagerDelegate , CBPeripheralDelegate>
//Bioland-BPM
@property (nonatomic, strong) NSString *deviceName;

@property (nonatomic, strong) NSString *characteristicUUID;

@property (nonatomic, strong) NSString *serviceUUID;

//中心
@property (nonatomic,strong) CBCentralManager *centralManager;
//外设
@property (nonatomic,strong) CBPeripheral *peripheral;
//特征
@property (nonatomic, strong) CBCharacteristic *characteristic;

@property (nonatomic, assign) BOOL needWriteData;

@property (nonatomic, strong) NSMutableSet<CBPeripheral*> *peripheralList;


@end

@implementation DRBluetoothManager

-(NSMutableSet<CBPeripheral *> *)peripheralList{
    if (!_peripheralList) {
        _peripheralList = [[NSMutableSet alloc] init];
    }
    return  _peripheralList;
}

+(instancetype)manager{
    static DRBluetoothManager *manager = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

- (void)startConnectWithName:(NSString *)name serviceUUID:(nonnull NSString *)serviceUUID  characteristicUUID:(nonnull NSString *)uuid needWriteData:(BOOL)isNeed
{
    if (self.centralManager && self.peripheral) {
        [self.centralManager cancelPeripheralConnection:self.peripheral];
        self.peripheral = nil;
    }
    self.deviceName = name;
    self.characteristicUUID = uuid;
    self.serviceUUID = serviceUUID;
    self.needWriteData = isNeed;
    //初始化中心端,开始蓝牙模块
    self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
    self.centralManager.delegate = self;
    NSMutableArray *array = [NSMutableArray array];
    for (CBPeripheral *per in self.peripheralList) {
        [array addObject:per.identifier];
    }
    [self.centralManager retrievePeripheralsWithIdentifiers:array];
}

-(void) _updateState:(DeviceStyle) style{
    if (self.delegate && [self.delegate respondsToSelector:@selector(didUpdateDevice:)])
    {
        //控制器更新UI
        [self.delegate didUpdateDevice:style];
    }
}


//断开连接
- (void)endConnect
{
    if (self.peripheral) {
        [self.centralManager cancelPeripheralConnection:self.peripheral];
        self.peripheral = nil;
        self.centralManager = nil;
        [self.centralManager stopScan];
    }
}

#pragma mark - VCMethod
//读数据
- (void)readFromPeripheral
{
    NSLog(@"读数据");
    [self.peripheral readValueForCharacteristic:self.characteristic];
}

//写数据
- (void)writeToPeripheralWith:(NSString *)instruct
{
    NSLog(@"写数据");
    NSData *data = [[OSZDataTool sharedTool] hexToBytes:instruct];
    [self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithoutResponse];
}

//监听数据
- (void)notifyPeripheral
{
    NSLog(@"监听数据");
    [self.peripheral setNotifyValue:YES forCharacteristic:self.characteristic];
}


#pragma mark - CBCentralManagerDelegate
// 状态更新后触发
-(void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case CBManagerStatePoweredOff:
            //还没开启蓝牙
            [SVProgressHUD showErrorWithStatus:@"请打开蓝牙"];
            break;
        case CBManagerStatePoweredOn:
            break;
        case CBManagerStateResetting:
            break;
        case CBManagerStateUnauthorized:
            break;
        case CBManagerStateUnknown:
            break;
        case CBManagerStateUnsupported:
            [SVProgressHUD showErrorWithStatus:@"当前设备不支持蓝牙"];
            break;
        default:
            break;
    }
    NSLog(@"更新蓝牙状态：%ld",(long)central.state);
    [central scanForPeripheralsWithServices:nil options:nil];
}

// 扫描到外部设备后触发的代理方法//多次调用的
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(nonnull CBPeripheral *)peripheral advertisementData:(nonnull NSDictionary<NSString *,id> *)advertisementData RSSI:(nonnull NSNumber *)RSSI
{
    //    扫描到的外部设备
    [self _updateState:DeviceStyleScanning];
    NSString *msg = [NSString stringWithFormat:@"信号强度: %@, 外设: %@", RSSI, peripheral];
    NSLog(@"%@",msg);
    if ([peripheral.name isEqualToString:self.deviceName])
    {
        //连接外部设备
        NSLog(@"开始连接外部设备:%@",self.deviceName);
        self.peripheral = peripheral;
        [self.centralManager connectPeripheral:peripheral options:nil];
        //停止搜索
        [central stopScan];
        [self _updateState:(DeviceStyleLinging)];
    }
}

//连接失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"%@",error.localizedDescription);
    [self.centralManager connectPeripheral:self.peripheral options:nil];
}

// 当中心端连接上外设时触发
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"连接上外设%@",peripheral.name);
    //停止搜索
    [central stopScan];

    self.peripheral.delegate = self;
//    [self.peripheralList addObject:peripheral];
    [self.peripheral discoverServices:nil];
    [self _updateState:(DeviceStyleLingSucceed)];

}


//如果连接上的两个设备突然断开了，程序里面会自动回调下面的方法
-   (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"设备断开重连");
    [self.centralManager connectPeripheral:self.peripheral options:nil];
    //当断开时做缺省数据处理
    // 让它自动重连
    [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:self.serviceUUID]] options:nil];
}

#pragma mark - CBPeripheralDelegate
// 外设端发现了服务时触发
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    NSLog(@"peripheral服务：%@",peripheral.services);
    if (error)
    {
        NSLog(@"%@",error.localizedDescription);
        return;
    }
    for (CBService *service in peripheral.services)
    {
        //只找有用的服务  1000 or Device Information
        NSLog(@"UUID:%@",service.UUID);
        if ([service.UUID isEqual:[CBUUID UUIDWithString:self.serviceUUID]])
        {
            NSLog(@"发现服务：%@", service);
            [peripheral discoverCharacteristics:nil forService:service];
        }
    }
}


//从服务获取特征
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    NSLog(@"特征%@",service.characteristics);
    
    for (CBCharacteristic *characteristic in service.characteristics)
    {
        // -------- 读特征的处理 --------
        if ([characteristic.UUID.description isEqualToString: self.characteristicUUID])
        {
            NSLog(@"处理读特征:%@",self.characteristicUUID);
            [peripheral readValueForCharacteristic:characteristic];
        }
//
        // -------- 写特征的处理 --------
        if ([characteristic.UUID.description isEqualToString: @"1001"] && self.needWriteData)
        {
            NSString *dataString = [self getSendHex:0];
            NSLog(@"写特征->>>%@",dataString);
            //向外设发送0001命令
            NSData *data = [[OSZDataTool sharedTool] convertHexStrToData:dataString];
            NSLog(@"data>>>>>>%@",data);
            self.characteristic = characteristic;
            [self.peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
            
        }
        
        // -------- 订阅特征的处理 --------
        // 订阅特性，当数据频繁改变时，一般用它， 不用readValueForCharacteristic
        if ([characteristic.UUID.description isEqualToString: self.characteristicUUID])
        {
            NSLog(@"处理了订阅特征:%@",self.characteristicUUID);
            self.characteristic = characteristic;
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
        }
    }
}


//收到数据
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    //控制器去处理
    if (self.delegate && [self.delegate respondsToSelector:@selector(receivedValue:)])
    {
        [self.delegate receivedValue:characteristic.value.copy];
    }
    if ([characteristic.UUID.description isEqualToString: @"1001"] && self.needWriteData) {
        NSString *dataString = [self getSendHex:3];
        NSData *data = [[OSZDataTool sharedTool] convertHexStrToData:dataString];
        NSLog(@"data>>>>>>%@",data);
        [self.peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
    }
    
}


// 写特征CBCharacteristicWriteWithResponse的数据写入的结果回调
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if (error) {
        NSLog(@"数据写入失败: %@", error);
    } else {
        NSLog(@"数据写入成功");
        [self.peripheral readValueForCharacteristic:characteristic];

    }
}

-(NSString *) getSendHex:(int) statue{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yy-MM-dd-HH-mm-ss"];
    NSString *dateString = [formatter stringFromDate:[NSDate date]];
    NSArray *timeArray = [dateString componentsSeparatedByString:@"-"];
    //下面是10进制的
    int index0 = 90;//5A
    int index1 = 10;//整个包的长度，包括 CheckSum 部分
    int index2 = statue; //下行指令类型 读取血糠仪信息 00// 读取血糖仪测量数据 03
    int index3 = [timeArray[0] intValue];
    int index4 = [timeArray[1] intValue];
    int index5 = [timeArray[2] intValue];
    int index6 = [timeArray[3] intValue];
    int index7 = [timeArray[4] intValue];
    int index8 = [timeArray[5] intValue];
    int index9 = index0 + index1 + index2 + index3 + index4 + index5 + index6 + index7 + index8 + 2;
    Byte *bt= (Byte*)malloc(9);
    bt[0] = index0;
    bt[1] = index1;
    bt[2] = index2;
    bt[3] = index3;
    bt[4] = index4;
    bt[5] = index5;
    bt[6] = index6;
    bt[7] = index7;
    bt[8] = index8;
    Byte *bt2 = (Byte*)malloc(1);
    bt2[0] = index9;
    NSString *hexString = [NSString stringWithFormat:@"%@%@%@%@%@%@%@%@%@",
                           [[NSString alloc]initWithFormat:@"%02lx",(long)bt[0]],
                           [[NSString alloc]initWithFormat:@"%02lx",(long)bt[1]],
                           [[NSString alloc]initWithFormat:@"%02lx",(long)bt[2]],
                           [[NSString alloc]initWithFormat:@"%02lx",(long)bt[3]],
                           [[NSString alloc]initWithFormat:@"%02lx",(long)bt[4]],
                           [[NSString alloc]initWithFormat:@"%02lx",(long)bt[5]],
                           [[NSString alloc]initWithFormat:@"%02lx",(long)bt[6]],
                           [[NSString alloc]initWithFormat:@"%02lx",(long)bt[7]],
                           [[NSString alloc]initWithFormat:@"%02lx",(long)bt[8]]];
    NSString *hexIndex9 = [NSString stringWithFormat:@"%@",[[NSString alloc]initWithFormat:@"%02lx",(long)bt2[0]] ];
    int len = [hexIndex9 length];
    NSString *i9 = [hexIndex9 substringFromIndex:len - 2];
    return [[NSString stringWithFormat:@"%@%@",hexString, i9] uppercaseString];
}


@end


